var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var util = require('util');

var Port = new Schema({
	name : String,
	device : {
		type : Schema.ObjectId,
		ref : 'Device'
	},
	sysId : {
		type : String,
		unique : true
	},
	type : {
		type : String,
		enum : [ 'Boolean', 'Number' ]
	},
	direction : {
		type : String,
		enum : [ 'Input', 'Output', 'Bidirectional' ]
	},
	smoothing : Number,
	description : String,
	value : {}
});

/**
 * Compound unique index of parent device and remote port name
 * 
 * @mamberOf Port
 * @type index
 * @static
 */
Port.index({
	device : 1,
	name : 1
}, {
	unique : true
});

Port.pre('remove', function(next) {
	log.debug("Remove pre");
	var self = this;

	model.Device.findOne({
		_id : self.device
	}, function(e, device) {
		log.debug("Number of Ports " + device.ports.length);

		for ( var p = 0; p < device.ports.length; p++) {
			log.debug('Port: ' + device.ports[p] + ", my ID: " + self._id);
			if (device.ports[p].toString() == self._id.toString()) {
				log.debug("Match");
				device.ports.splice(p, 1);
				log.debug("Done?");
				device.save(next);
				break;
			}
		}
	});
});

// Port.pre('save', function(next) {
// var self = this;
//	
// model.Device.findById((self.device._id || self.device), function(e, device) {
// if(device) {
// util.puts("Updating Device " + device.name + " for port " + self.name);
// // device.set();
// next();
// }
// });
// });

Port.methods.create = function(callback) {
	var self = this;

	log.debug("Saved Port");
	model.Device.findOne({
		_id : self.device
	}, function(e, device) {
		log.debug("Port " + self._id);

		log.debug("Add to Device " + device._id);
		device.ports.push(self._id);
		log.debug("Pushed");
		device.save();
	});

	callback = callback || function() {
	};
	this.save(callback);
};

model.Port = mongoose.model('Port', Port);

tasks.on('link_update', function(id, value) {
	log.debug("Updating Port");
	model.Port.update({
		_id : id
	}, {
		value : value
	}, function(e) {
		if (e)
			log.error(e, 'Models/Port:106');
	});
});
